package org.example.demo.service.backend.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.demo.dto.ShipmentDTO;
import org.example.demo.raw.Shipment;
import org.example.demo.service.backend.ShipmentBackendService;
import org.fisco.bcos.sdk.abi.datatypes.generated.tuples.generated.Tuple8;
import org.fisco.bcos.sdk.client.Client;
import org.fisco.bcos.sdk.model.TransactionReceipt;
import org.fisco.bcos.sdk.transaction.model.exception.ContractException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigInteger;

@Slf4j
@Service
public class IShipmentBackendService implements ShipmentBackendService {

    @Value("${system.contract.shipmentAddress}")
    private String contractAddress;

    @Autowired
    private Client client;

    @Override
    public boolean addShipment(ShipmentDTO shipmentDTO) {
        Shipment shipment = Shipment.load(contractAddress, client, client.getCryptoSuite().getCryptoKeyPair());
        TransactionReceipt transactionReceipt = shipment.addShipment(
                shipmentDTO.getId(),
                shipmentDTO.getCarrier(),
                shipmentDTO.getFrom(),
                shipmentDTO.getTo()
        );
        return transactionReceipt.isStatusOK();
    }

    @Override
    public ShipmentDTO getShipment(int id) throws ContractException {
        Shipment shipment = Shipment.load(contractAddress, client, client.getCryptoSuite().getCryptoKeyPair());
        Tuple8<BigInteger, BigInteger, BigInteger, String, String, String, BigInteger, BigInteger> shipmentTuple = shipment.getShipment(new BigInteger(String.valueOf(id)));
        return new ShipmentDTO(
                shipmentTuple.getValue1(), // id
                shipmentTuple.getValue3(), // carrier_id
                shipmentTuple.getValue4(), // from
                shipmentTuple.getValue5(), // to
                shipmentTuple.getValue6()  // status
        );
    }

    @Override
    public boolean updateShipmentStatus(int id, String status) {
        Shipment shipment = Shipment.load(contractAddress, client, client.getCryptoSuite().getCryptoKeyPair());
        // 这里假设carrier_id为0，实际应用中需要根据业务逻辑获取承运商ID
        TransactionReceipt transactionReceipt = shipment.updateShipment(
                BigInteger.ZERO, // carrier_id
                new BigInteger(String.valueOf(id)), // shipment_id
                status
        );
        return transactionReceipt.isStatusOK();
    }

    @Override
    public String getStatus(int id) throws ContractException {
        Shipment shipment = Shipment.load(contractAddress, client, client.getCryptoSuite().getCryptoKeyPair());
        return shipment.getStatus(new BigInteger(String.valueOf(id)));
    }
}
